﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Microsoft.EntityFrameworkCore;
using Abp.Domain.Repositories;
using Abp.AutoMapper;
using Abp.Application.Services;
using Abp.UI;
using Abp.IdentityFramework;
using Abp.Linq.Extensions;
using Abp.Collections.Extensions;
using Abp.Extensions;
using SW.YUNCMS.Dtos;

namespace SW.YUNCMS.AppService
{
    /// <summary>
    /// 泛型实体服务实现基类
    /// </summary>
    /// <typeparam name="R">实体</typeparam>
    /// <typeparam name="I">请求Dto</typeparam>
    /// <typeparam name="E">编辑Dto</typeparam>
    /// <typeparam name="O">输出Dto</typeparam>
    public class AppService<CU,R,I, E, O,Tkey> : IAppService<CU,I, E, O> where R:Abp.Domain.Entities.Auditing.FullAuditedEntity<Tkey> where CU:CreateOrUpdateInputDto<E,Tkey> where I:Dtos.PagedSortedAndFilteredInputDto where O:class where E:EditInputDto<Tkey>
    {
        public  IRepository<R,Tkey> repository;

        

        public async Task  CreateOrUpdate(CU input)
        {


            if (input.EditDto.Id.Equals(0))
            {
              await  UpdateAsync(input.EditDto);
            }
            else
            {
                await CreateAsync(input.EditDto);
            }
        }

        public Task Delete(I input)
        {
            throw new NotImplementedException();
        }

        public async Task<PagedResultDto<O>> GetPagedAsync(I input)
        {
            
            

            //TODO:添加过滤条件
            
            var query = repository.GetAll();
            var count =await query.CountAsync();
            var q =await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
            var dto=  q.MapTo<List<O>>();
            return new PagedResultDto<O>(count, dto);



        }
        public  async Task CreateAsync(E input)
        {
          var entity=  input.MapTo<R>();
          await repository.InsertAsync(entity);
        }
        public async Task UpdateAsync(E input)
        {
            var entity = repository.GetAsync(input.Id);
            var dto=await input.MapTo(entity);
            await repository.UpdateAsync(dto);
        }
     
    }
}
